package app;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.xml.XMLConstants;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.xml.sax.SAXException;

public class App {

    private static JAXBContext jaxbContext;
    private static Marshaller jaxbMarshaller;
    private static Unmarshaller jaxbUnmarshaller;
    private static File roomsFile;
    private static Validator validator;
    private static SchemaFactory schemaFactory;

    public static void main(String[] args) throws SAXException, JAXBException {

        Room room = new Room("Conference", 5);

        try {

            roomsFile = new File("rooms.xml");
            FileOutputStream outStream = new FileOutputStream(roomsFile);

        } catch (IOException e) {
            System.out.println("IOException: " + e.getMessage());
        }

        try {

            jaxbContext = JAXBContext.newInstance(Room.class);
            jaxbMarshaller = jaxbContext.createMarshaller();
            jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

            schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Schema schema = schemaFactory.newSchema(new File("schema.xsd"));
            jaxbMarshaller.setSchema(schema);

            jaxbMarshaller.marshal(room, System.out);
            jaxbMarshaller.marshal(room, roomsFile);

        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

        try {

            jaxbUnmarshaller = jaxbContext.createUnmarshaller();
            Schema schema2 = schemaFactory.newSchema(new File("schema_2.xsd"));
            jaxbUnmarshaller.setSchema(schema2);
            Room room1 = (Room) jaxbUnmarshaller.unmarshal(roomsFile);
            System.out.println(room1);

        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

    }
}
